import jsCookie from "js-cookie"
import { reactive, computed } from "vue"

import { useSearchStore } from "../../store/search"
import { handleArticleStatus } from "../../service/article/index"
import { zlDialog } from "../../utils/zlDialog"

const searchStore = useSearchStore()
const searchType = computed(() => searchStore.searchType)

export const useDepHooks = (props: any) => {
  const cardInfo = reactive<any>({
    id: props.data.id || "",
    isLike: !!(props.data.isLike * 1),
    isCollect: !!(props.data.isCollect * 1),
    likeNum: props.data.likeNum || 0,
    collectNum: props.data.collectNum || 0,
    vierNum: props.data.browseNum || 0
  })
  const handleIconClick = async (type: 'love' | 'favorite' | "share") => {
    if (!jsCookie.get("token")) return zlDialog()
    const currKeys = ['', '']
    let currType: "1" | "2" = "1"
    switch (type) {
      case "love":
        currKeys[0] = 'isLike'
        currKeys[1] = "likeNum"
        currType = "1"
        break;
      case "favorite":
        currKeys[0] = 'isCollect'
        currKeys[1] = "collectNum"
        currType = "2"
        break;
      case "share":
        const shareUrl = window.location.origin + `/detail?id=${cardInfo.id}&searchType=${searchStore.searchType}`

        await window.navigator.clipboard.writeText(shareUrl);

        ElMessage({
          type: "success",
          message: "资讯链接复制成功,快去分享给好友吧~"
        })

        return false
        break;
    }

    // 发送网络请求
    const result = await handleArticleStatus({ sourceId: cardInfo.id, sourceType: searchStore.searchType, type: currType })

    if (result.code != "200" || !result.code) return false;



    cardInfo[currKeys[1]] = cardInfo[currKeys[0]] ? cardInfo[currKeys[1]] - 1 : cardInfo[currKeys[1]] + 1
    cardInfo[currKeys[0]] = !cardInfo[currKeys[0]]

    if (type === "love" && cardInfo[currKeys[0]]) {
      ElNotification({
        title: '点赞',
        message: '点赞成功~',
        type: 'success',
      })
    } else if (type === "love" && !cardInfo[currKeys[0]]) {
      ElNotification({
        title: '取消点赞',
        message: '已成功取消点赞~',
        type: 'success',
      })
    } else if (type === "favorite" && cardInfo[currKeys[0]]) {
      ElNotification({
        title: '收藏',
        message: '收藏成功~',
        type: 'success',
      })
    } else if (type === "favorite" && !cardInfo[currKeys[0]]) {
      ElNotification({
        title: '取消收藏',
        message: '已成功取消收藏~',
        type: 'success',
      })
    }
  }
  const goDetailPage = (id: string, searchType: any) => {
    window.open(`${location.origin}/detail?id=${id}&searchType=${searchType}`, "_blank")
  }


  return { cardInfo, handleIconClick,goDetailPage,searchType }
}
